<?php

namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Api\CommonController;
use App\Models\Users;
use Illuminate\Foundation\Auth\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class UserController extends CommonController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        try {
            $params = $request->all();

            $params = json_decode($params['params'], true);

            $where = $params['search'] ?? [];
            $limit = $params['pageSize'] ?? '10';
            $offset = ($params['pageCode'] - 1) * $limit ?? '1';

            //获取数据
            $data = Users::select('*')
                ->where($where)
                ->limit($limit)
                ->offset($offset)
                ->get();


            //循环给予每个角色一个权限数组
            foreach ($data as $key => $value) {
                //获取当前角色的所有允许权限

                $data[$key]['roleData'] = $value->getRoleNames();
            }

            //获取数据总数
            $total = Users::count();

            return $this->successReturn(200, [
                'total' => $total,
                'list' => $data
            ]);

        } catch (\Exception $e) {
            return $this->errorReturn(500, $e->getMessage());
        }
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        try {
            $data = $request->params;

            $params = [
                'username' => $data['username'],
                'email' => $data['email'],
                'password' => $data['password'],
                'password_confirmation' => $data['password_confirmation'],
                'actived' => $data['actived'] ?? 1,
                'roleData' => $data['roleData'],
            ];
            //配置验证
            $rules = [
                'username' => 'required|min:4|max:18|unique:users',
                'email' => 'required|email',
                'password' => 'required|confirmed:password_confirmation',
                'password_confirmation' => 'required',
                'actived' => 'required',
                'roleData' => 'required|array',
            ];
            //错误信息
            $message = [
                'username.required' => '[username]缺失',
                'username.unique' => '该用户名已经存在',
                'email.required' => '[email]缺失',
                'password.required' => '[password]缺失',
                'confirm_password.required' => '[confirm_password]缺失',
                'actived.required' => '[actived]缺失',
                'roleData.required' => '[roleData]缺失',
                'roleData.array' => '[roleData]必须为数组',
                'username.min' => '[username]最少4位',
                'username.max' => '[username]最多18位',
                'password.confirmed' => '两次密码输入不一致',
            ];

            $this->verifyParams($params, $rules, $message);

            DB::beginTransaction();

//            dd($params);

            $user = new Users();
            $user->username = $params['username'] ?? '';
            $user->email = $params['email'] ?? '';
            $user->password = Hash::make($params['password']) ?? '';
            $user->actived = $params['actived'] ?? '1';
            $user->avatar = $data['avatar'] ?? '';

            if (!$user->save()) $this->throwExp('添加用户失败');

            foreach ($params['roleData'] as $key => $val) {
                $user->assignRole($val);
            }

            DB::commit();

            //正确返回信息
            return $this->successReturn(200, '添加用户成功');

        } catch (\Exception $e) {
            return $this->errorReturn('400', $e->getMessage());

        }
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        try {
            $data = $request->all();

            $params = [
                'username' => $data['username'],
                'email' => $data['email'],
                'password' => $data['password'] ?? null,
                'password_confirmation' => $data['password_confirmation'] ?? null,
                'actived' => $data['actived'] ?? 1,
                'roleData' => $data['roleData'],
            ];
            //配置验证
            $rules = [
                'username' => 'required|min:4|max:18',
                'email' => 'required|email',
                'password' => 'required|confirmed:password_confirmation|min:4|max:18',
                'password_confirmation' => 'required',
                'actived' => 'required',
                'roleData' => 'required|array',
            ];
            //错误信息
            $message = [
                'username.required' => '[username]缺失',
                'email.required' => '[email]缺失',
                'password.required' => '[password]缺失',
                'password.min' => '[password]最少6位',
                'password.min' => '[password]最多18位',
                'confirm_password.required' => '[confirm_password]缺失',
                'actived.required' => '[actived]缺失',
                'roleData.required' => '[roleData]缺失',
                'roleData.array' => '[roleData]必须为数组',
                'username.min' => '[username]最少4位',
                'username.max' => '[username]最多18位',
                'password.confirmed' => '两次密码输入不一致',
            ];

            if (is_null($params['password'])) unset($rules['password']);
            unset($rules['password_confirmation']);

            // 表单验证
            $this->verifyParams($params, $rules, $message);

            //开始事务
            DB::beginTransaction();


            $user = Users::find($id);
            $user->username = $params['username'] ?? '';
            $user->email = $params['email'] ?? '';
            $user->password = isset($params['password']) ? Hash::make($params['password']) : $user->password;
            $user->actived = $params['actived'] ?? '1';
            $user->avatar = $data['avatar'] ?? '';

            if (!$user->save()) $this->throwExp('修改用户失败');

            //将所有角色移除
            DB::table('model_has_roles')
                ->where('model_id', $id)
                ->delete();

            foreach ($params['roleData'] as $key => $val) {
                $user->assignRole($val);
            }

            //提交事务
            DB::commit();

            //正确返回信息
            return $this->successReturn(200, '修改用户成功');

        } catch (\Exception $e) {
            return $this->errorReturn('400', $e->getMessage());

        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (!intval($id)) return $this->errorReturn(500, '参数错误');

        if (!Users::destroy($id)) return $this->errorReturn(500, '删除失败');


        return $this->successReturn(200, '删除成功');
    }
}
